import {
  pageVoteRange,
  updateVoteRangeState,
  voteRangeInit,
} from '@/services/api/api-assess-month-emphasize-vote';
import { ActionType, DrawerForm, ProCard, ProList } from '@ant-design/pro-components';
import { Button, Flex, Result, Spin, Tag } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddVoteRange from './AddVoteRange';
import TableRankRecord from './TableRankRecord';
import TableVoteResult from './TableVoteResult';
import styles from './TableVoteStyle.less';
dayjs.extend(customParseFormat);

interface TableVoteProps {}

const TableVote: React.FC<TableVoteProps> = ({}) => {
  const access = useAccess();

  const [loading, setLoadingState] = useState<boolean>(true);

  const actionRefProList = useRef<ActionType>();

  const [searchParam, setSearchParamState] = useState({
    dataName: '',
    rangeId: '',
    datahubLevelId: '2000',
    reportType: 1,
    datahubChannelId: '',
  });

  const [rangeInitData, setRangeInitDataState] = useState<AssessMonthEmphasizeVoteData.RangeInit>();

  const [selectRange, setSelectRangeState] = useState<AssessMonthEmphasizeVoteData.RangePage>();

  const [revote, setRevoteState] = useState<number>(0);

  const [latestRangeState, setLatestRangeState] = useState<number>(0);
  const [showVoteResults, setShowVoteResults] = useState<number>(0);

    
  /**
   * 获取 初始化 数据
   * @param key
   */
  const loadRankInit = async () => {
    try {
      const response = await voteRangeInit();
      if (response.code === 0) {
        const data = response.data;

        setSearchParamState({
          ...searchParam,
          rangeId: data.latestRangeId,
        });

        setRangeInitDataState(data);
        setLatestRangeState(data.latestRangeState)
        setShowVoteResults(data.showVoteResults)


        setLoadingState(false);
      }
    } catch (error) {
      setLoadingState(false);
    }
  };

  const containerView = (range: AssessMonthEmphasizeVoteData.RangePage) => {
    if (range == undefined) {
      return <></>;
    }

    if (range.state == 1) {
      if (range.isParticipate == 1) {
        if (revote == 1) {
          return (
            <TableRankRecord
              revote={revote}
              range={range}
              onSave={function (): void {
                setRevoteState(0);
                actionRefProList.current?.reload();
              }}
              onRefurbish={function (): void {}}
            />
          );
        } else {
          return (
            <TableVoteResult
              range={range}
              onRevote={function (): void {
                setRevoteState(1);
              }}
            />
          );
        }
      } else {
        return (
          <TableRankRecord
            revote={revote}
            range={range}
            onSave={function (): void {
              setRevoteState(0);
              actionRefProList.current?.reload();
            }}
            onRefurbish={function (): void {}}
          />
        );
      }
    } else {
      return (
        <TableVoteResult
          range={range}
          onRevote={function (): void {
            setRevoteState(1);
          }}
        />
      );
    }
  };

  return (
    <DrawerForm
      key="table_assess_exhibition_vote"
      title={'三好作品投票'}
      drawerProps={{
        width: 1200,
        maskClosable: true,
        destroyOnClose: true,
        extra: access.传播质效x投票x配置x管理员 && (
          <AddVoteRange
            onRefurbish={function (): void {}}
            onSave={function (): void {
              setRangeInitDataState(undefined);
              loadRankInit();
              actionRefProList.current?.reloadAndRest();
            }}
          />
        ),
      }}
      layout="horizontal"
      trigger={<Button type="primary">三好作品投票</Button>}
      submitter={false}
      onOpenChange={(visible: boolean) => {
        if (visible) {
          loadRankInit();
        } else {
          setLoadingState(true);
          setRangeInitDataState(undefined);
          setSelectRangeState(undefined);
          setRevoteState(0);
        }
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={loading}
      >
        {rangeInitData == undefined ? (
          <Result title="暂无投票" />
        ) : (
          <ProCard split="vertical">
            <ProCard colSpan="300px" title={''} ghost>
              <ProList<AssessMonthEmphasizeVoteData.RangePage>
                actionRef={actionRefProList}
                request={async (params, sorter) => {
                  const response = await pageVoteRange({
                    ...params,
                    type: '',
                  });

                  response.data.data.forEach((item) => {
                    if (item.id == searchParam.rangeId) {
                      setSelectRangeState(item);
                    }
                  });

                  return {
                    data: response.data?.data,
                    success: true,
                    total: response.data?.total,
                  };
                }}
                rowKey="id"
                options={false}
                pagination={{
                  showQuickJumper: true,
                  showSizeChanger: false,
                  defaultPageSize: 12,
                }}
                search={false}
                metas={{
                  title: {
                    dataIndex: 'name',
                    render(dom, entity, index, action, schema) {
                      return (
                        <div
                          style={{
                            width: '299px',
                            paddingLeft: '18px',
                          }}
                        >
                          <Flex justify={'space-between'} align={'flex-start'}>
                            <div
                              style={{
                                marginBottom: '6px',
                              }}
                            >
                              <Tag color={entity.state == 1 ? '#87d068' : '#f50'}>
                                {entity.state == 1 ? '进行中' : '已结束'}
                              </Tag>
                              <Tag
                                color={
                                  entity.type == 1
                                    ? 'gold'
                                    : entity.type == 2
                                    ? 'green'
                                    : entity.type == 3
                                    ? 'blue'
                                    : 'purple'
                                }
                              >
                                {entity.type == 1
                                  ? '年'
                                  : entity.type == 2
                                  ? '季'
                                  : entity.type == 3
                                  ? '月'
                                  : '周'}
                              </Tag>
                              <Tag color={entity.isParticipate == 0 ? 'orange' : 'green'}>
                                {entity.isParticipate == 0 ? '未投票' : '已投票'}
                              </Tag>
                            </div>
                            {access.传播质效x投票x配置x管理员 && (
                              <a
                                style={{
                                  marginRight: '18px',
                                }}
                                onClick={async () => {
                                  const response = await updateVoteRangeState({
                                    voteRangeId: entity.id,
                                  });

                                  if (response.code === 0) {
                                    const data = response.data;
                                    actionRefProList.current?.reload();
                                  }
                                }}
                              >
                                {entity.state == 1 ? '关闭' : '开启'}
                              </a>
                            )}
                          </Flex>

                          <div
                            style={{
                              marginBottom: '2px',
                            }}
                          >
                            {entity.name} | {entity.startDate} - {entity.endDate}
                          </div>
                          <span
                            style={{
                              fontSize: '14px',
                              color: '#00000073',
                              fontWeight: 'normal',
                            }}
                          >
                            {entity.createdTime}
                          </span>
                        </div>
                      );
                    },
                  },
                }}
                rowClassName={(row: AssessMonthCollectArticleRangeData.RangePage) => {
                  return row.id === searchParam.rangeId ? styles['split-row-select-active'] : '';
                }}
                onRow={(record) => {
                  return {
                    onClick: () => {
                      if (record.id) {
                        setSearchParamState({
                          ...searchParam,
                          rangeId: record.id,
                        });
                        setRevoteState(false);
                        setSelectRangeState(record);
                      }
                    },
                  };
                }}
              />
            </ProCard>
            <ProCard
              ghost
              bodyStyle={{
                paddingLeft: 18,
              }}
            >
              {selectRange && containerView(selectRange)}
            </ProCard>
          </ProCard>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default TableVote;
